const express = require('express');
const router = express.Router();
const superagent = require('superagent');
require("superagent-charset")(superagent);
const dayjs = require("dayjs");

const stockModel = require('../model/stock');
const unitModel = require('../model/unit');


async function getStockDetail(code){
    let result = await superagent.get("https://datacenter.eastmoney.com/securities/api/data/v1/get")
        .set('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36')
        .query({
            reportName: "RPT_F10_ORG_BASICINFO",
            columns: "SECUCODE,SECURITY_CODE,SECURITY_NAME_ABBR,SECURITY_TYPE",
            filter: `(SECURITY_CODE="${code}")`,
            pageNumber: 1,
            pageSize: 10,
            client: 'PC',
        })
    let data = JSON.parse(result.text)
    if (data.code === 0){
        console.log("获取详情成功")
        return data.result.data[0];
    } else {
        console.error("获取详情失败")
        return null;
    }
}

async function getSectorYear(secucode){
    let result = await superagent.get("https://datacenter.eastmoney.com/securities/api/data/v1/get")
        .set('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36')
        .query({
            reportName: "RPT_F10_FN_MAINOP",
            columns: "SECUCODE,REPORT_DATE",
            distinct: "REPORT_DATE",
            filter: `(SECUCODE="${secucode}")`,
            pageNumber: 1,
            pageSize: 1,
            sortColumns: "REPORT_DATE",
            sortTypes: -1,
            client: 'PC',
        })

    let data = JSON.parse(result.text);

    if (data.code === 0){
        console.log("获取年份成功")
        return data.result.data[0];
    } else {
        console.error("获取年份失败")
        return null;
    }
}

async function getStockBussiness(secucode,reportdate){

    let result = await superagent.get("https://datacenter.eastmoney.com/securities/api/data/v1/get")
        .set('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36')
        .query({
            reportName: "RPT_F10_FN_MAINOP",
            columns: "SECUCODE,SECURITY_CODE,REPORT_DATE,MAINOP_TYPE,ITEM_NAME,MAIN_BUSINESS_INCOME,MBI_RATIO,MAIN_BUSINESS_COST,MBC_RATIO,MAIN_BUSINESS_RPOFIT,MBR_RATIO,GROSS_RPOFIT_RATIO,RANK",
            filter: `(SECUCODE="${secucode}")(REPORT_DATE='${reportdate}')`,
            pageNumber: 1,
            pageSize: 20,
            sortColumns: "MAINOP_TYPE,RANK",
            sortTypes: "1,1",
            client: 'PC',
        })

    let data = JSON.parse(result.text);

    if (data.code === 0){
        console.log("获取主营业务成功")
        return JSON.stringify(data.result.data);
    } else {
        console.error("获取主营业务失败")
        return null;
    }
}



router.get("/search",async (req,res)=>{

    let {code} = req.query;

    try {
        let row = await stockModel.findOne({code: {$eq: code}}).select("-__v");

        if (row){

            res.send({
                code: 0,
                data: row
            })
        } else {
            let stock = {
                code: "",
                secucode: "",
                type: "",
                name: "",
                business: "",
                eval: "",
                description: "",
                reportDate: ""
            };

            let detail = await getStockDetail(code);

            if (detail){
                stock.code = code;
                stock.secucode = detail['SECUCODE'];
                stock.type = detail['SECURITY_TYPE'];
                stock.name = detail['SECURITY_NAME_ABBR'];

                detail = await getSectorYear(stock.secucode);

                if (detail){
                    stock.reportDate = dayjs(detail['REPORT_DATE']).format('YYYY-MM-DD');

                    detail = await getStockBussiness(stock.secucode,stock.reportDate);

                    if (detail){
                        stock.business = detail;
                    }
                }


            }

            res.send({
                code: 0,
                data: stock
            })

        }


    } catch(e){
        res.send({
            code: 1,
            msg: e.toString()
        })
    }


})


router.post("/create",async (req,res)=>{

    let { boardId } = req.body;

    try {
        let row = await stockModel.findOne({secucode: {$eq: req.body.secucode}});

        if (row){

            await stockModel.findByIdAndUpdate(row._id.toString(),{$set: req.body},{ new: true,runValidators: true });

        } else {
            row = await stockModel.create({
                code: req.body.code,
                secucode: req.body.secucode,
                type: req.body.type,
                name: req.body.name,
                business: req.body.business,
                eval: req.body.eval,
                description: req.body.description,
                reportDate: req.body.reportDate
            })
        }


        // 作为unit加入面板
        await unitModel.create({
            belong: boardId,
            name: req.body.name,
            code: req.body.secucode,
            stockCode: req.body.code,
            klines: []
        })



        res.send({
            code: 0,
            data: row
        })
    } catch(e){

        res.send({
            code: 1,
            msg: e.toString()
        })
    }

})


router.get("/get", async (req,res)=>{

    let {stockCode} = req.query;

    try {
        let row = await stockModel.findOne({code:stockCode}).select("-__v");

        let detail = await getSectorYear(row.secucode);


        if(detail){
            //如果报告日期不一样要更新
            let reportDate = dayjs(detail["REPORT_DATE"]).format('YYYY-MM-DD');
            if (reportDate!==row.reportDate){

                let business = await getStockBussiness(row.secucode,reportDate);

                await stockModel.findByIdAndUpdate(row._id.toString(),{
                    reportDate: reportDate,
                    business: business
                },{ new: true,runValidators: true });

                row = await stockModel.findOne({code:stockCode}).select("-__v");
            }
        }


        res.send({
            code: 0,
            data: row
        })
    } catch(e){
        res.send({
            code: 1,
            msg: e.toString()
        })
    }




})


module.exports = router;
